﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using FunctionalCLR.Core.Logging;

namespace Zove.Desktop {
    public class MessageGridView : DataGridView {

        public List<LoggingMessage> Messages {
            get;
            set;
        }

        public void BindMessages() {
            this.Rows.Clear();

            foreach (LoggingMessage message in this.Messages) {
                this.Rows.Add(
                    new string[] { 
                        message.Description,
                        message.LineNumber.ToString(),
                        message.FileName});
            }
        }

        public MessageGridView()
            : base() {
            this.AddColumn("Description");
            this.AddColumn("Line");
            this.AddColumn("Source");

            this.Dock = DockStyle.Fill;
            this.AllowUserToAddRows = false;
            this.AllowUserToDeleteRows = false;
            this.AllowUserToResizeRows = false;

            this.DoubleClick += new EventHandler(MessageGridView_DoubleClick);
        }

        public void MessageGridView_DoubleClick(object sender, EventArgs e) {
            DataGridViewRow r = this.Rows[this.SelectedCells[0].RowIndex];
            DataGridViewCell cs = r.Cells["ColSource"];
            string source = cs.Value.ToString();
            DataGridViewCell cl = r.Cells["ColLine"];
            int line = Convert.ToInt32(cl.Value.ToString());

            EditingForm editingForm = null;
            foreach (Form form in DesktopFormContext.Context.Values) {
                if(form.GetType().Equals(typeof(EditingForm))) {
                    editingForm = (EditingForm)form;

                    if (source.ToLower() == editingForm.ClassName.ToLower()) {
                        break;
                    } else {
                        editingForm = null;
                    }
                }
            }

            if (editingForm == null) {
                editingForm = DesktopFormContext.Context.Main.OpenEditWindow(source);
            } else {
                editingForm.BringToFront();
            }
            if (editingForm != null) {
                editingForm.CurrentLine = line;
            }
        }

        public void AddColumn(string name) {
            int index = this.Columns.Add("col" + name, name);

            DataGridViewColumn column = this.Columns[index];
            column.ReadOnly = true;
        }
    }
}
